package com.jxwifi.cloud.quickclean.cleanermap;

import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusPath;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RidePath;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RideStep;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.basicactivity.BasicActivity;
import com.idroid.utils.NoDoubleClickListener;
import com.jxwifi.cloud.quickclean.R;
import com.jxwifi.cloud.quickclean.app.ClientBasicActivity;
import com.jxwifi.cloud.quickclean.app.LocationGaoDe;
import com.jxwifi.cloud.quickclean.app.StateUtils;
import com.jxwifi.cloud.quickclean.bean.OrderDetailsBean;
import com.jxwifi.cloud.quickclean.mapUtils.BusRouteOverlay;
import com.jxwifi.cloud.quickclean.mapUtils.DrivingRouteOverlay;
import com.jxwifi.cloud.quickclean.mapUtils.RideRouteOverlay;
import com.jxwifi.cloud.quickclean.utils.TitleClient;
import com.jxwifi.cloud.quickclean.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CleaningMapActivity extends ClientBasicActivity implements CleaningMapView,RouteSearch.OnRouteSearchListener{

    @Bind(R.id.mp_map_work)
    MapView mMapView;
    //初始化地图控制器对象
    AMap aMap;
    @Bind(R.id.tv_map_work_time_hours)
    TextView mTvMapWorkTimeHours;
    @Bind(R.id.tv_map_work_time)
    TextView mTvMapWorkTime;
    @Bind(R.id.tv_map_work_distance)
    TextView mTvMapWorkDistance;

    private OrderDetailsBean mOrderDetails;
    private CleaningMapPresenter mPresenter;
    public RouteSearch  mRouteSearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cleaning_map);
        ButterKnife.bind(this);
        openEventBus();
        mOrderDetails=(OrderDetailsBean)getIntent().getExtras().getSerializable("order_details");
        mPresenter=new CleaningMapPresenter(mBaseContext,this);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        initHead();
        //mPresenter.initView();
        mRouteSearch = new RouteSearch(this);
        mRouteSearch.setRouteSearchListener(this);
        setRouteCarListener(3);
    }

    private void initHead() {
        TitleClient holder = new TitleClient(ButterKnife.findById(this, R.id.lin_client_title));
        holder.defineTitle("保洁员位置");
        holder.defineLeft(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                onBackPressed();
            }
        });
    }

    @OnClick({R.id.tv_img_map_work_phone})
    void clickCK(View v){
        switch (v.getId()){
            case R.id.tv_img_map_work_phone:
                mPresenter.CleaningTell();
                break;
        }
    }

    @Override
    public TextView getMapWorkTimeHours() {
        return mTvMapWorkTimeHours;
    }

    @Override
    public TextView getMapWorkDistance() {
        return mTvMapWorkDistance;
    }

    @Override
    public TextView getMapWorkTime() {
        return mTvMapWorkTime;
    }

    @Override
    public MapView getMapView() {
        return mMapView;
    }

    @Override
    public OrderDetailsBean getBean() {
        return mOrderDetails;
    }

    @Override
    public void onFailure(int errorCode, String msg) {
        Toast toast = Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
        ToastUtils.showMyToast(toast, 3000);
    }

    /**
     * 规划线路
     * type 0 驾车 1 公交 2 步行 3 骑行
     *
     * @param type
     */
    private void setRouteCarListener(int type) {
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        //清除防止重复显示
        aMap.clear();

        //模拟起始点与目的经纬度（如：深圳市）
        RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
                new LatLonPoint(Double.valueOf(mOrderDetails.getOrderInfo().getLat()), Double.valueOf(mOrderDetails.getOrderInfo().getLon())),
                new LatLonPoint(Double.valueOf(mOrderDetails.getCleanerInfo().getLat()), Double.valueOf(mOrderDetails.getCleanerInfo().getLon())));
       // Log.w("oushuhua", "lat=" + LocationGaoDe.getLatitude() + "lon=" + LocationGaoDe.getLongitude() + "citycode" + LocationGaoDe.getCityCode());
        //Log.w("oushuhua", "lat1=" + Double.valueOf(morderFromBean.getLat()) + "lon1=" + Double.valueOf(morderFromBean.getLon()));

        //驾车：第一个参数表示fromAndTo包含路径规划的起点和终点，drivingMode表示驾车模式(支持20种模式  -在PathPlanningStrategy类中定义)
        //第三个参数表示途经点（最多支持16个），第四个参数表示避让区域（最多支持32个），第五个参数表示避让道路
        //模式链接：http://lbs.amap.com/api/android-navi-sdk/guide/route-plan/drive-route-plan
       /* LatLng marker1 = new LatLng(((22.5587+22.5587)/2), (119.8727+113.8950)/2);
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(marker1));*/
        if (type == 0) {
            RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, RouteSearch.DrivingDefault, null,
                    null, "");// 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
            mRouteSearch.calculateDriveRouteAsyn(query);
        } else if (type == 1) {
            //公交：fromAndTo包含路径规划的起点和终点，RouteSearch.BusLeaseWalk表示公交查询模式
            //第三个参数表示公交查询城市区号，第四个参数表示是否计算夜班车，0表示不计算,1表示计算
            RouteSearch.BusRouteQuery query1 = new RouteSearch.BusRouteQuery(fromAndTo, RouteSearch.BusLeaseWalk, LocationGaoDe.getCityCode(), 1);
            //
            mRouteSearch.calculateBusRouteAsyn(query1);

        } else if (type == 2) {

        } else if (type == 3) {
            RouteSearch.RideRouteQuery query3 = new RouteSearch.RideRouteQuery(
                    fromAndTo, RouteSearch.RidingDefault);
            mRouteSearch.calculateRideRouteAsyn(query3);
        }

    }

    //公交路线设置
    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {
        if (i == 1000) {
            if (busRouteResult.getPaths().size() != 0) {
                BusPath busPath = busRouteResult.getPaths().get(0);//取数据泪飙中的第一条数据
                setBusRoute(busPath, busRouteResult.getStartPos(), busRouteResult.getTargetPos());
                float distance = busPath.getDistance() / 1000;
                long duration = busPath.getDuration() / 60;
                //需步行距离
                float walkdistance = busPath.getWalkDistance() / 1000;
                //行车的距离
                float busdistance = busPath.getBusDistance() / 1000;
                //成本、费用（其中walkdistance+busdistance=distance 行车+步行=总距离）
                float cost = busPath.getCost();
                //content.setText("\n距离/公里：" + distance + "\n时间/分：" + duration + "\n步行距离/公里：" + walkdistance + "\n行车距离/公里：" + busdistance + "\n成本、费用：" + cost);
            } else {
                LatLng latLng = new LatLng(Double.valueOf(mOrderDetails.getOrderInfo().getLat()),
                        Double.valueOf(mOrderDetails.getOrderInfo().getLon()));
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17));
            }
        } else {
            Log.e(TAG, "onBusRouteSearched: 路线规划失败");
        }
    }

    //驾车路线设置
    @Override
    public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {
        if (i == 1000) {
            if (driveRouteResult.getPaths().size() != 0) {
                DrivePath drivePath = driveRouteResult.getPaths().get(0);//取数据泪飙中的第一条数据
                DriveRouteResult mDriveRouteResult = driveRouteResult;
                //setDriveRoute(busPath, driveRouteResult.getStartPos(), driveRouteResult.getTargetPos());
                DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(
                        mBaseContext, aMap, drivePath,
                        mDriveRouteResult.getStartPos(),
                        mDriveRouteResult.getTargetPos(), null);
                drivingRouteOverlay.setNodeIconVisibility(false);//设置节点marker是否显示
                drivingRouteOverlay.setIsColorfulline(true);//是否用颜色展示交通拥堵情况，默认true
                drivingRouteOverlay.removeFromMap();
                drivingRouteOverlay.addToMap();
                drivingRouteOverlay.zoomToSpan();
            } else {
                LatLng latLng = new LatLng(Double.valueOf(mOrderDetails.getOrderInfo().getLat()),
                        Double.valueOf(mOrderDetails.getOrderInfo().getLon()));
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17));
            }

        } else {
            Log.e(TAG, "onBusRouteSearched: 路线规划失败");
        }

    }

    //步行路线设置
    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

    }

    //骑车路线设置
    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {
        if (i == 1000) {
            RidePath ridePath = rideRouteResult.getPaths().get(0);
            setRideRoute(ridePath, rideRouteResult.getStartPos(), rideRouteResult.getTargetPos());
            float distance = ridePath.getDistance() / 1000;
            long duration = ridePath.getDuration() / 60;
            mPresenter.initView(distance,duration);

        } else {
            Log.i(TAG, "onRideRouteSearched: 路线规划失败");
        }
    }

    /**
     * 公交规划线路
     */
    private void setBusRoute(BusPath busPath, LatLonPoint start, LatLonPoint end) {
        BusRouteOverlay busRouteOverlay = new BusRouteOverlay(this, aMap, busPath, start, end);
        busRouteOverlay.removeFromMap();//去掉DriveLineOverlay上的线段和标记。
        busRouteOverlay.addToMap();//添加驾车路线添加到地图上显示。
        busRouteOverlay.zoomToSpan();//移动镜头到当前的视角。
        busRouteOverlay.setNodeIconVisibility(true);//是否显示路段节点图标
    }

    /**
     * 骑行规划线路
     */
    private void setRideRoute(RidePath ridePath, LatLonPoint start, LatLonPoint end) {
        RideRouteOverlay rideRouteOverlay = new RideRouteOverlay(this, aMap, ridePath, start, end);
        rideRouteOverlay.removeFromMap();
        rideRouteOverlay.addToMap();
        rideRouteOverlay.zoomToSpan();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

}
